package pku.ss.movieSystem.struts.action;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import daos.Session;
import daos.User;

import pku.ss.movieSystem.services.IBookTicketsService;
import pku.ss.movieSystem.struts.form.SeatsSelectForm;

public class SeatsSelectAction extends DispatchAction{
	
	private IBookTicketsService bookTicketsService;
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward getSessionInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		response.setContentType("text/html; charset=utf-8");
		try {
			request.setCharacterEncoding("utf8");
			response.setCharacterEncoding("utf8");
			
			PrintWriter out = response.getWriter();
			JSONObject jsonObj = new JSONObject();
			
			int sessionId = Integer.parseInt(request.getParameter("sessionId"));
			String sessionInfo = bookTicketsService.getSessionJSONInfo(sessionId);
			
			jsonObj.put("sessionInfo", sessionInfo);
			out.print(jsonObj.toString());
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/** 
	 * Method execute
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward orderSeats(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		SeatsSelectForm seatsSelectForm = (SeatsSelectForm)form;
		String sessionSeats = seatsSelectForm.getSessionSeats();
		String orderSeatNos = seatsSelectForm.getOrderSeatNos();
		if(orderSeatNos.charAt(0) == ','){
			orderSeatNos = orderSeatNos.substring(1);
		}
		int sessionId = seatsSelectForm.getSessionId();
		
		bookTicketsService.updateSessionSeats(sessionId, sessionSeats);
	
		Session session = bookTicketsService.getSessionInfo(sessionId);
		String[] seatNos = orderSeatNos.split(",");	
		int quantity = seatNos.length;
		
		float amount = session.getPrice() * quantity;
		request.setAttribute("amount", amount);
		//int userId = ((User)request.getSession(true).getAttribute("currentUser")).getUserId();

		HttpSession userSession = request.getSession(true);
		int userId = ((User)userSession.getAttribute("user")).getUserId();
		bookTicketsService.addOrder(sessionId, userId, orderSeatNos, seatNos.length, amount);
		return mapping.findForward("payment");
	}
	
	public void setBookTicketsService(IBookTicketsService bts) {
		this.bookTicketsService = bts;
	}

}
